package com.studykun.client.ui;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;

public class CategoryChart extends FlowPanel
{
  private List<Integer> quantities_ = new ArrayList<Integer>();

  public CategoryChart() {
    this.getElement().setClassName("progressFrame");
  }
  
  public void setCategoryQuantities(
      final List<Integer> quantities) {
    quantities_.clear();
    quantities_.addAll(quantities);
    redraw();
  }
  
  public void setCategoryWidgets(
      final List<Widget> widgets) {
    this.clear();
    for (final Widget widget : widgets) {
      this.add(widget);
    }
    redraw();
  }
  
  private int getTotalQuantity() {
    int total = 0;
    
    for (int count : quantities_) {
      total += count;
    }
    
    return total;
  }
  
  private String measure(
      final int quantity,
      final int total)
  {
    return (10000 * quantity / total) / 100.0 + "%";
  }
  
  private void redraw()
  {
    final int totalQuantity = getTotalQuantity();
    
    if (totalQuantity == 0) {
      return;
    }
    
    int accumulator = 0;
    final int count = Math.min(this.getWidgetCount(), quantities_.size());
    
    for (int i = 0; i < count; ++i) {
      final String width = measure(quantities_.get(i), totalQuantity);
      final String left = measure(accumulator, totalQuantity);
      final Element eCategory = getWidget(i).getElement();
      eCategory.getStyle().setProperty("left", left);
      eCategory.getStyle().setProperty("width", width);
      eCategory.setAttribute("isZero", width.equals("0%") ? "true" : "false");
      eCategory.getStyle().setProperty("position", "absolute");
      eCategory.getStyle().setProperty("height", "100%");
      
      accumulator += quantities_.get(i);
    }
  }
}
